﻿using System;
using System.Collections.Generic;
using System.Linq;
using Fisharoo.DataAccess.Interfaces;
using System.ComponentModel.Composition;

namespace Fisharoo.DataAccess
{
    [Export(typeof(IPermissionRepository))]
    public class PermissionRepository : IPermissionRepository
    {
        private Connection conn;
        public PermissionRepository()
        {
            conn = new Connection();    
        }

        public List<Permission> GetPermissionsByAccountID(Int32 AccountID)
        {
            using (FisharooDataContext dc = conn.GetContext())
            {
                
                var permissions = from p in dc.Permissions
                                    join ap in dc.AccountPermissions on p.PermissionID equals ap.PermissionID
                                    join a in dc.Accounts on ap.AccountID equals a.AccountID
                                    where a.AccountID == AccountID
                                    select p;
                
                return permissions.ToList();
            }
        }

        public List<Permission> GetPermissionByName(string Name)
        {

            using (FisharooDataContext dc = conn.GetContext())
            {
                var permissions = from p in dc.Permissions.Where(p=>p.Name.Equals(Name))
                                  select p;
 
                return permissions.ToList();

            }
        }

        public List<Permission> GetPermissionByID(Int32 PermissionID)
        {
            List<Permission> returnPermissions = new List<Permission>();

            using(FisharooDataContext dc = conn.GetContext())
            {
                var permissions = from p in dc.Permissions.Where(p=>p.PermissionID.Equals(PermissionID))
                                   select p;

                 return returnPermissions.ToList();    
            }
        }

        public void SavePermission(Permission permission)
        {
            using(FisharooDataContext dc = conn.GetContext())
            {
                if(permission.PermissionID > 0)
                {
                    dc.Permissions.AddObject(permission);
                }
                else
                {
                    dc.Permissions.ApplyCurrentValues(permission);
                }
                dc.SaveChanges();
            }
        }

        public void DeletePermission(Permission permission)
        {
            using(FisharooDataContext dc = conn.GetContext())
            {
                dc.DeleteObject(permission);
                dc.SaveChanges();

            }
        }
    }
}
